<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\DB;

use Illuminate\Http\Request;

class IncomeController extends Controller
{

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //查询用户游戏数据
        $promotion = DB::table('promotion')
            ->select('id', 'url', 'code', 'single', 'total', 'start_date', 'end_date', 'state','promoter')
            ->whereDate('start_date', '<=',date('Y-m-d'))
            ->whereDate('end_date', '>',date('Y-m-d'))
            ->where(function ($query) {
                $query->orWhere('url', 'like', '%'.@$_GET['search'].'%');
                $query->orWhere('code', 'like', '%'.@$_GET['search'].'%');
                $query->orWhere('single', 'like', '%'.@$_GET['search'].'%');
                $query->orWhere('total', 'like', '%'.@$_GET['search'].'%');
                $query->orWhere('start_date', 'like', '%'.@$_GET['search'].'%');
                $query->orWhere('end_date', 'like', '%'.@$_GET['search'].'%');
            })
            ->orderBy('id', 'desc')
            ->paginate(15)
            ->withPath('?search=' . @$_GET['search'] . '');

        return view('user.income.index',['promotion'=>$promotion]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
       //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {

        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function record()
    {
        //查询用户游戏数据
        $income_record = DB::table('income_record')
            ->select('id', 'code', 'ip', 'address', 'single', 'money', 'time')
            ->where('income_person', Auth::user()->username)
            ->where(function ($query) {
                $query->orWhere('code', 'like', '%'.@$_GET['search'].'%');
                $query->orWhere('ip', 'like', '%'.@$_GET['search'].'%');
                $query->orWhere('address', 'like', '%'.@$_GET['search'].'%');
                $query->orWhere('single', 'like', '%'.@$_GET['search'].'%');
                $query->orWhere('money', 'like', '%'.@$_GET['search'].'%');
                $query->orWhere('time', 'like', '%'.@$_GET['search'].'%');
            })
            ->orderBy('id', 'desc')
            ->paginate(18)
            ->withPath('?search=' . @$_GET['search'] . '');

        return view('user.income.record',['income_record'=>$income_record]);
    }

    /**
     * Redirect to url by its code.
     *
     * @param string $code
     *
     * @return \Illuminate\Http\Response
     */
    public function url()
    {
        //查询推广真实链接
        $promotion = DB::table('promotion')
            ->select('id', 'url', 'single', 'total', 'start_date', 'end_date', 'promoter')
            ->where('code', @$_GET['code'])
            ->get();

        //查询用户ID
        $user = DB::table('users')
            ->select('id', 'email', 'money')
            ->where('id', @$_GET['id'])
            ->get();

        //查询推广记录中的IP
        $ip = DB::table('promotion_record')
            ->select('id', 'ip', 'time')
            ->where('url', $promotion[0]->url)
            ->where('ip', $this->getClientIP() )
            ->where('income_person', $user[0]->email )
            ->whereDate('time', date('Y-m-d') )
            ->get();

        if( $promotion[0]->start_date > date('Y-m-d') && $promotion[0]->end_date < date('Y-m-d') ){
            return response()->json(['message' => 'The given data was invalid.', 'errors' => ['date' => ['推广未开始或已结束。']]], 422);
        }

        //查询剩余额度
        if( $promotion[0]->total < $promotion[0]->single ){
            return response()->json(['message' => 'The given data was invalid.', 'errors' => ['total' => ['推广额度不足。']]], 422);
        }

        //如果跳转地址与用户名 同时存在有效
        if($promotion->count() &&  $user->count() ){

            //如果当天IP已经点击过，就不在获得佣金
            if( !$ip->count() ){
                //扣除推广总额
                DB::table('promotion')->where('code', @$_GET['code'])->decrement('total', $promotion[0]->single);

                //增加推广用户金额
                DB::table('users')->where('id', @$_GET['id'])->increment('money', $promotion[0]->single);

                //推广记录
                DB::table('promotion_record')->insert([
                    'url' => $promotion[0]->url,
                    'ip' => $this->getClientIP(),
                    'address' => /*$this->getIpInfo($this->getClientIP()) ? $this->getIpInfo($this->getClientIP()) :*/ '未知' ,
                    'single' => $promotion[0]->single,
                    'total' => $promotion[0]->total-$promotion[0]->single,
                    'time' => date('Y-m-d H:i:s'),
                    'promoter' => $promotion[0]->promoter,
                    'income_person' => $user[0]->email
                ]);

                //收入记录
                DB::table('income_record')->insert([
                    'code' => @$_GET['code'],
                    'ip' => $this->getClientIP(),
                    'address' => /*$this->getIpInfo($this->getClientIP()) ? $this->getIpInfo($this->getClientIP()) : */'未知' ,
                    'single' => $promotion[0]->single,
                    'money' => $user[0]->money+$promotion[0]->single,
                    'time' => date('Y-m-d H:i:s'),
                    'income_person' => $user[0]->email
                ]);

            }

            //return redirect($promotion[0]->url);
            return view('user.income.url',['url'=>$promotion[0]->url]);
        }else{
            return response()->json(['message' => 'The given data was invalid.', 'errors' => ['code' => ['推广失败。']]], 422);
        }

    }

    //获取客户IP
    function getClientIP()
    {
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
            $ip = getenv("HTTP_CLIENT_IP");
        else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
            $ip = getenv("REMOTE_ADDR");
        else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
            $ip = $_SERVER['REMOTE_ADDR'];
        else
            $ip = "unknown";
        return($ip);
    }

    //获取IP省份信息
    function getIpInfo($ip = '')
    {
        $host = "https://ipquery.market.alicloudapi.com";
        $path = "/query";
        $method = "GET";
        $appcode = "add032716ed8492f8f597120e813c6db";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        $querys = "ip=".$ip."";
        $bodys = "";
        $url = $host . $path . "?" . $querys;

        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);  //隐藏head信息
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }

        $ipInfo = json_decode(curl_exec($curl),true);

        $prov = $ipInfo['data']['prov'];   //省
        $city = $ipInfo['data']['city'];   //市
        $area = $ipInfo['data']['area'];   //县
        $isp = $ipInfo['data']['isp'];     //运营商

        if( $prov === '' ){
            $address = '本机局域网';
        } else if( $prov === $city ){
            $address = $city.$area.' '.$isp;
        } else{
            $address = $prov.$city.$area.' '.$isp;
        }

        return $address;

    }

}
